<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="../css/bootstrap.css" />
		<script type="text/javascript" src="../js/vue.min.js"></script>
	</head>

	<body>
		<div id="app">
			<cmt-box @func="loadComments"></cmt-box>
			
			<ul calss="list-group">
				<li class="list-group-item" v-for="item in list" :key="item.id">
					<span class="badge">评论人:{{item.user}}</span> {{item.content}}
				</li>
			</ul>
		</div>

		<template id="temp">
			<div>
				<div class="form-group">
					<label>评论人:</label>
					<input type="text" class="form-control" v-model="user" />
				</div>

				<div class="form-group">
					<label>评论内容:</label>
					<textarea class="form-control" v-model="content"></textarea>
				</div>

				<div class="form-group">
					<input type="button" value="发表评论" class="btn btn-primary" @click="postComment" />
				</div>
			</div>
		</template>
	</body>
	<script>
		var commentBox = {
			//子组件里的data必须是一个function
			data() {
				return {
					user: '',
					content: ''
				}
			},
			template: "#temp",
			methods: {
				postComment() {
					/*
					 * 发表评论的业务逻辑
					 * 1.评论的数据存放到localStorage中
					 * 		localStorage.setItem('cmts','')
					 * 2.先组织处一个最新的评论数据对象
					 * 3.localStorage 只支持存放字符串数据
					 */
					var comment = {
						id: Date.now(),
						user: this.user,
						content: this.content
					}
					var list = JSON.parse(localStorage.getItem('cmts') || '[]')
					list.unshift(comment);
					localStorage.setItem('cmts', JSON.stringify(list));
					this.user=this.content='';
					this.$emit("func");
				}
			}

		};

		var vue = new Vue({
			el: "#app",
			data: {
				list: []
			},
			created(){
				this.loadComments();
			},
			methods: {
				loadComments(){
					var list=JSON.parse(localStorage.getItem("cmts")||'[]')
					this.list=list;
				}
			},
			components: {
				'cmt-box': commentBox
			}
		});
	</script>

</html>